package com.fjl.gson.test;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class JsonToList
{

	public static void main(String[] args)
	{
		jsonToLst2();

	}

	public static void jsonToLst1()
	{
		// String json =
		// "[{'name':'huangbiao','age':15},{'name':'liumei','age':14}]";
		String json = "[{\"id\":\"1\",\"age\":0,\"name\":\"one\"},{\"id\":\"2\",\"age\":0,\"name\":\"two\"}]";
		System.out.println(json);

		List<Person> personLst = getListLocationInfo1(json);
		// List<Person> personLst = GsonUtil.parseJsonArrayWithGson(json,
		// Person.class);
		for (Person person : personLst)
		{
			System.out.println(person.getName());
		}
	}

	public static void jsonToLst2()
	{
		// String json =
		// "[{'name':'huangbiao','age':15},{'name':'liumei','age':14}]";
		String json = "[{'name':'/huangbiao','age':15},{'name':'liumei','age':14}]";
		System.out.println(json);

		List<Person> personLst = getListLocationInfo1(json);
		for (Person person : personLst)
		{
			System.out.println(person.getName());
		}
	}

	public static void jsonToLst3()
	{
		String json = "['1','2','3']";
		System.out.println(json);

		Gson gson = new Gson();
		List<String> strList = gson.fromJson(json, new TypeToken<List<String>>()
		{
		}.getType());

		for (String str : strList)
		{
			System.out.println(str);
		}
	}

	public static void jsonToLst4()
	{
//		{title=null, attributes=[],
		String json = "{'name':'huangbiao','age':15}";
		System.out.println(json);

//		Person person = getListLocationInfo2(json);
		Person person = GsonUtil.parseJsonWithGson(json, Person.class);
		System.out.println(person.getName());
	}

	/**
	 * 解析JSON数据，还原成Person对象列表 Param : jsonString 从服务器获得的Json数据 解析代码，一个最外层是[]
	 * 
	 * @param jsonString
	 * @return List<LocationInfo>
	 */
	public static List<Person> getListLocationInfo1(String jsonString)
	{
		List<Person> list = new ArrayList<Person>();
		Gson gson = new Gson();
		list = gson.fromJson(jsonString, new TypeToken<List<Person>>()
		{
		}.getType());

		// 解析代码，一个最外层是{}
		// LocationInfo fromJson = gson.fromJson(jsonString,
		// LocationInfo.class);

		return list;
	}

	/**
	 * 解析JSON数据，还原成Person对象列表 Param : jsonString 从服务器获得的Json数据 解析代码，一个最外层是[]
	 * 
	 * @param jsonString
	 * @return List<LocationInfo>
	 */
	public static Person getListLocationInfo2(String jsonString)
	{
		Person person;
		Gson gson = new Gson();

		// 解析代码，一个最外层是{}
		person = (Person) gson.fromJson(jsonString, Person.class);

		return person;
	}
}
